package com.ct.rbac.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ct.rbac.mapper.SysRoleApisMapper;
import com.ct.rbac.orm.SysRoleApisDO;
import com.ct.rbac.repository.ISysRoleApisRespontory;
import com.ct.repository.commons.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author Auto Generator
 * @since 2023-08-13
 */
@Service
public class SysRoleApisRespontoryImpl extends BaseServiceImpl<SysRoleApisMapper, SysRoleApisDO> implements ISysRoleApisRespontory {


    /**
     * 判断角色是否被权限引入
     * @param roleId
     * @return
     */
    @Override
    public Boolean countRoleApi(Long roleId){
        LambdaQueryWrapper<SysRoleApisDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleApisDO::getRoleId,roleId);
        return this.count(lambdaQueryWrapper) > 0;
    }

    /**
     * 判断权限是否被角色引入
     * @param apiId
     * @return
     */
    @Override
    public Boolean countApiRole(Long apiId){
        LambdaQueryWrapper<SysRoleApisDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleApisDO::getApiId,apiId);
        return this.count(lambdaQueryWrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean bindApis(Long roleId, List<Long> apis) {
        // 先删除角色对应的菜单
        LambdaQueryWrapper<SysRoleApisDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysRoleApisDO::getRoleId,roleId);
        this.remove(lambdaQueryWrapper);

        // 添加角色对应的菜单
        List<SysRoleApisDO> sysRoleApisDOS = apis.stream().map(apisId -> {
            SysRoleApisDO sysRoleApisDO = new SysRoleApisDO();
            sysRoleApisDO.setRoleId(roleId);
            sysRoleApisDO.setApiId(apisId);
            return sysRoleApisDO;
        }).collect(Collectors.toList());

        return this.saveBatch(sysRoleApisDOS);
    }
}
